document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const resourcesTableBody = document.querySelector('#resources-table tbody');
    const searchInput = document.getElementById('resource-search');
    const refreshButton = document.getElementById('refresh-btn');
    const resourceTypeSelect = document.getElementById('resource-type');
    const sortOptionSelect = document.getElementById('sort-option');
    const goUpButton = document.getElementById('go-up-btn');
    
    // 当前路径变量（默认为根目录）
    let currentPath = '';
    // 路径历史记录，用于返回上一级
    const pathHistory = [];
    
    // 存储当前媒体信息
    let currentMediaInfo = {
        method: null,
        data: null,
        details: null
    };
    // 存储当前选择的资源
    let currentResource = null;
    // 存储当前下载的海报文件名，用于临时文件管理
    let currentPosterFilename = null;
    // 标记是否已经生成NFO文件（生成后应保留海报）
    let nfoGenerated = false;
    
    // 全局变量用于刮削相关信息
    let currentScrapeMovieName = '';
    let currentScrapeMethod = '';
    
    // 返回上一级按钮事件监听
    if (goUpButton) {
        goUpButton.addEventListener('click', goToParentDirectory);
    }
    
    // 初始化页面
    // 初始化刮削模态框
    initScrapeModal();
    initScrapeMethodModal();
    initSearchResultsModal();
    initResourceDetailModal();  // 确保详情模态框初始化
    
    // 点击刷新按钮加载资源
    if (refreshButton) {
        refreshButton.addEventListener('click', function() {
            // 强制刷新，不使用缓存
            loadLocalResources(true);
        });
        
        // 页面加载后直接触发刷新按钮的功能
        setTimeout(() => {
            if (refreshButton && typeof refreshButton.click === 'function') {
                refreshButton.click();
            }
        }, 100);
    }
    
    // 搜索输入框事件
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                loadLocalResources();
            }
        });
        
        // 防抖搜索 - 添加防抖函数实现
        searchInput.addEventListener('input', debounce(function() {
            loadLocalResources();
        }, 500));
    }
    
    // 资源类型选择事件
    if (resourceTypeSelect) {
        resourceTypeSelect.addEventListener('change', function() {
            loadLocalResources();
        });
    }
    
    // 排序选项选择事件
    if (sortOptionSelect) {
        sortOptionSelect.addEventListener('change', function() {
            loadLocalResources();
        });
    }
    
    // 防抖函数实现
    function debounce(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(context, args), wait);
        };
    }
    
    // 通知函数实现
    window.showNotification = function(message, type = 'info') {
        // 简单实现，可根据需要替换为更复杂的通知组件
        const notification = document.createElement('div');
        notification.className = `fixed bottom-4 right-4 px-4 py-2 rounded shadow-lg ${
            type === 'error' ? 'bg-red-500 text-white' :
            type === 'success' ? 'bg-green-500 text-white' :
            'bg-blue-500 text-white'
        }`;
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.style.opacity = '0';
            notification.style.transition = 'opacity 0.3s ease';
            setTimeout(() => notification.remove(), 300);
        }, 3000);
    };
    
    // 加载本地资源函数
    function loadLocalResources(forceRefresh = false) {
        // 检查必要元素是否存在
        if (!resourceTypeSelect || !sortOptionSelect || !searchInput) return;
        
        // 获取查询参数
        const resourceType = resourceTypeSelect.value;
        const searchQuery = searchInput.value.trim();
        const sortOption = sortOptionSelect.value;
        
        // 显示当前路径
        updateCurrentPathDisplay();
        
        // 生成缓存键
        const cacheKey = `local_resources_${resourceType}_${sortOption}_${searchQuery}`;
        
        // 如果不是强制刷新，尝试从localStorage获取缓存数据
        if (!forceRefresh) {
            const cachedData = localStorage.getItem(cacheKey);
            if (cachedData) {
                try {
                    const parsedData = JSON.parse(cachedData);
                    // 检查数据是否在有效期内（5分钟）
                    if (Date.now() - parsedData.timestamp < 5 * 60 * 1000) {
                        renderResources(parsedData.resources);
                        return;
                    }
                } catch (e) {
                    console.error('解析缓存数据失败:', e);
                    // 解析失败时继续从API获取
                }
            }
        }
        
        // 显示加载状态
        showLoading(true);
        
        // 构建API URL
        let apiUrl = `/api/local-resources/list?type=${encodeURIComponent(resourceType)}&sort=${encodeURIComponent(sortOption)}&recursive=false`;
        if (searchQuery) {
            apiUrl += `&q=${encodeURIComponent(searchQuery)}`;
        }
        // 添加当前路径参数
        if (currentPath) {
            apiUrl += `&path=${encodeURIComponent(currentPath)}`;
        }
        
        // 发送请求到API
        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                showLoading(false);
                
                if (data.success && data.data) {
                    // 缓存数据到localStorage
                    localStorage.setItem(cacheKey, JSON.stringify({
                        resources: data.data,
                        timestamp: Date.now()
                    }));
                    renderResources(data.data);
                } else {
                    renderErrorMessage(data.message || '加载资源失败');
                }
            })
            .catch(error => {
                console.error('加载本地资源失败:', error);
                showLoading(false);
                renderErrorMessage('加载资源失败: ' + error.message);
                window.showNotification('加载资源失败: ' + error.message, 'error');
            });
    }
    
    // 当刮削成功后，清除相关缓存，以便刷新页面时能看到最新数据
    function clearRelatedCache(resourcePath) {
        // 检查必要元素是否存在
        if (!resourceTypeSelect || !sortOptionSelect) return;
        
        // 获取当前的查询参数
        const resourceType = resourceTypeSelect.value;
        const sortOption = sortOptionSelect.value;
        
        // 清除当前查询参数下的所有缓存
        for (let key in localStorage) {
            if (key.startsWith('local_resources_') && 
                key.includes(`_${resourceType}_`) && 
                key.includes(`_${sortOption}_`)) {
                localStorage.removeItem(key);
            }
        }
    }
    
    // 更新当前路径显示
    function updateCurrentPathDisplay() {
        // 查找或创建路径显示元素
        let pathDisplayElement = document.getElementById('current-path-display');
        
        if (!pathDisplayElement) {
            // 查找资源列表标题元素的父容器
            const resourceListContainer = document.querySelector('section:nth-of-type(2) .bg-white');
            if (resourceListContainer) {
                // 查找表格元素
                const tableContainer = resourceListContainer.querySelector('.overflow-x-auto');
                if (tableContainer) {
                    // 创建路径显示元素
                    pathDisplayElement = document.createElement('div');
                    pathDisplayElement.id = 'current-path-display';
                    pathDisplayElement.className = 'mb-4 text-sm text-gray-600';
                    
                    // 插入到表格前
                    resourceListContainer.insertBefore(pathDisplayElement, tableContainer);
                }
            }
        }
        
        // 控制返回上一级按钮的显示
        if (goUpButton) {
            if (currentPath || pathHistory.length > 0) {
                goUpButton.classList.remove('hidden');
            } else {
                goUpButton.classList.add('hidden');
            }
        }
        
        if (pathDisplayElement) {
            // 构建路径显示内容
            if (!currentPath) {
                pathDisplayElement.innerHTML = '<i class="fa fa-home mr-1"></i> 根目录';
            } else {
                // 拆分路径并构建面包屑
                const pathParts = currentPath.split('\\');
                let breadcrumbHtml = '<i class="fa fa-home mr-1"></i> <a href="javascript:void(0);" class="path-part text-primary hover:underline" data-path="">根目录</a>';
                
                let currentSubPath = '';
                pathParts.forEach(part => {
                    if (part) {
                        currentSubPath += (currentSubPath ? '\\' : '') + part;
                        breadcrumbHtml += ' <i class="fa fa-chevron-right mx-1 text-gray-400"></i> ';
                        breadcrumbHtml += `<a href="javascript:void(0);" class="path-part text-primary hover:underline" data-path="${currentSubPath}">${part}</a>`;
                    }
                });
                
                pathDisplayElement.innerHTML = breadcrumbHtml;
                
                // 添加路径点击事件
                document.querySelectorAll('.path-part').forEach(link => {
                    link.addEventListener('click', function() {
                        const newPath = this.getAttribute('data-path');
                        navigateToPath(newPath);
                    });
                });
            }
        }
    }
    
    // 导航到指定路径
    function navigateToPath(path) {
        // 保存当前路径到历史记录（如果不是返回操作）
        if (currentPath !== path) {
            // 找到新路径在历史记录中的位置
            const historyIndex = pathHistory.indexOf(path);
            if (historyIndex >= 0) {
                // 如果路径已在历史记录中，移除之后的所有路径
                pathHistory.splice(historyIndex + 1);
            } else {
                // 否则添加到历史记录
                pathHistory.push(currentPath);
            }
        }
        
        // 更新当前路径
        currentPath = path;
        
        // 重新加载资源
        loadLocalResources(true);
        
        // 确保返回按钮可见
        if (goUpButton && pathHistory.length > 0) {
            goUpButton.classList.remove('hidden');
        }
    }
    
    // 返回上一级目录
    function goToParentDirectory() {
        if (pathHistory.length > 0) {
            currentPath = pathHistory.pop();
            loadLocalResources(true);
        }
    }
    
    // 渲染资源列表
    function renderResources(resources) {
        if (!resourcesTableBody) return;
        
        if (!resources || resources.length === 0) {
            resourcesTableBody.innerHTML = `
                <tr>
                    <td colspan="8" class="text-center p-8 text-gray-500">
                        <i class="fa fa-folder-open text-4xl mb-2"></i>
                        <p>未找到匹配的资源</p>
                    </td>
                </tr>
            `;
            return;
        }
        
        let html = '';
        resources.forEach(resource => {
            // 确定显示的图标和类型
            let iconClass = 'fa-file-o';
            let typeText = '文件';
            if (resource.is_folder) {
                iconClass = 'fa-folder';
                typeText = '文件夹';
            } else if (resource.is_mp4) {
                iconClass = 'fa-film';
            }
            
            // 格式化文件大小
            let sizeInfo = '文件夹';
            if (resource.is_file && resource.size !== null) {
                sizeInfo = formatFileSize(resource.size);
            }
            
            // 准备新增列的数据
            let hasPosterIcon = '<i class="fa fa-times text-red-500"></i>';
            let hasNfoIcon = '<i class="fa fa-times text-red-500"></i>';
            let hasMediaFileIcon = '<i class="fa fa-times text-red-500"></i>';
            let scrapeStatusHTML = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">未刮削</span>';
            
            if (resource.is_folder) {
                // 文件夹资源显示刮削相关信息
                hasPosterIcon = resource.has_poster ? '<i class="fa fa-check text-green-500"></i>' : hasPosterIcon;
                hasNfoIcon = resource.has_nfo ? '<i class="fa fa-check text-green-500"></i>' : hasNfoIcon;
                hasMediaFileIcon = resource.has_media_file ? '<i class="fa fa-check text-green-500"></i>' : hasMediaFileIcon;
                
                // 显示刮削状态
                if (resource.scrape_status && resource.scrape_status.is_scraped) {
                    scrapeStatusHTML = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">已刮削</span>';
                } else if (resource.scrape_status && resource.scrape_status.missing_items && resource.scrape_status.missing_items.length > 0) {
                    const missingItems = resource.scrape_status.missing_items.join(', ');
                    scrapeStatusHTML = `<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800" title="缺少：${missingItems}">未刮削</span>`;
                }
            } else if (resource.is_file && resource.is_video) {
                // 根据后端返回的刮削状态显示正确的状态
                if (resource.scrape_status && resource.scrape_status.is_scraped) {
                    scrapeStatusHTML = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">已刮削</span>';
                } else if (resource.scrape_status && resource.scrape_status.missing_items && resource.scrape_status.missing_items.length > 0) {
                    const missingItems = resource.scrape_status.missing_items.join(', ');
                    scrapeStatusHTML = `<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800" title="缺少：${missingItems}">未刮削</span>`;
                } else {
                    scrapeStatusHTML = '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">未刮削</span>';
                }
            }
            
            // 处理JSON字符串中的特殊字符
            const safeResourceData = JSON.stringify(resource)
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');
            
            html += `
                <tr class="border-b hover:bg-gray-50 transition-colors">
                    <td class="py-3 px-4">
                        <div class="flex items-center">
                            <i class="fa ${iconClass} text-gray-500 mr-3"></i>
                            <span class="${resource.is_folder ? 'folder-item cursor-pointer text-primary hover:underline' : 'text-gray-800'}" title="${resource.name || resource.short_play_name}" data-path="${resource.is_folder ? resource.path : ''}">
                                ${resource.short_play_name || resource.name || '未命名资源'}
                            </span>
                        </div>
                    </td>
                    <td class="py-3 px-4 text-gray-600">${typeText}</td>
                    <td class="py-3 px-4 text-gray-600">${sizeInfo}</td>
                    <td class="py-3 px-4 text-center">${hasPosterIcon}</td>
                    <td class="py-3 px-4 text-center">${hasNfoIcon}</td>
                    <td class="py-3 px-4 text-center">${hasMediaFileIcon}</td>
                    <td class="py-3 px-4">${scrapeStatusHTML}</td>
                    <td class="py-3 px-4">
                        <button class="bg-primary hover:bg-primary/90 text-white text-sm font-medium py-1 px-3 rounded-lg transition-all flex items-center scrape-btn" 
                                data-resource='${safeResourceData}'>
                            <i class="fa fa-scissors mr-1"></i> 刮削信息
                        </button>
                    </td>
                </tr>
            `;
        });
        
        // 清空表格体内容并设置新内容
        resourcesTableBody.innerHTML = html;
        
        // 解决方案：在函数外部只添加一次事件监听器
        // 但由于这是函数内部，我们需要一个安全的方法来避免重复绑定
        
        // 检查是否已经添加过事件监听器（通过自定义属性标记）
        if (!resourcesTableBody.hasAttribute('data-events-bound')) {
            // 添加事件监听
            resourcesTableBody.addEventListener('click', function(event) {
                // 处理刮削按钮点击
                const btn = event.target.closest('.scrape-btn');
                if (btn) {
                    try {
                        const resourceData = JSON.parse(btn.getAttribute('data-resource'));
                        scrapeMovieInfo(resourceData);
                    } catch (e) {
                        console.error('解析资源数据失败:', e);
                        window.showNotification('处理资源失败', 'error');
                    }
                    return; // 防止触发其他事件
                }
                
                // 处理文件夹点击
                const folderItem = event.target.closest('.folder-item');
                if (folderItem) {
                    const folderPath = folderItem.getAttribute('data-path');
                    if (folderPath && folderPath.trim() !== '') {
                        navigateToPath(folderPath);
                    }
                }
            });
            
            // 标记已添加事件监听器
            resourcesTableBody.setAttribute('data-events-bound', 'true');
        }
    }
    
    // 刮削电影信息 - 显示模态框
    function scrapeMovieInfo(resource) {
        // 保存当前资源信息（确保currentResource正确设置）
        currentResource = resource;
        console.log('已设置当前资源:', currentResource);
        
        // 检查模态框元素是否存在
        const scrapeModal = document.getElementById('scrape-modal');
        if (!scrapeModal) {
            console.error('刮削模态框元素不存在');
            return;
        }
        
        // 重置模态框状态
        const customNameContainer = document.getElementById('custom-name-container');
        const customMovieNameInput = document.getElementById('custom-movie-name');
        const folderRadio = document.querySelector('input[name="scrape-source"][value="folder-name"]');
        
        if (customNameContainer) customNameContainer.classList.add('hidden');
        if (customMovieNameInput) customMovieNameInput.value = '';
        if (folderRadio) folderRadio.checked = true;
        
        // 显示模态框
        scrapeModal.classList.remove('hidden');
    }
    
    // 初始化刮削模态框事件
    function initScrapeModal() {
        const scrapeModal = document.getElementById('scrape-modal');
        if (!scrapeModal) return; // 模态框不存在则不初始化
        
        const closeModalBtn = document.getElementById('close-scrape-modal');
        const cancelScrapeBtn = document.getElementById('cancel-scrape');
        const confirmScrapeBtn = document.getElementById('confirm-scrape');
        const customNameContainer = document.getElementById('custom-name-container');
        const customMovieNameInput = document.getElementById('custom-movie-name');
        const scrapeSourceRadios = document.querySelectorAll('input[name="scrape-source"]');
        
        // 关闭模态框
        function closeModal() {
            scrapeModal.classList.add('hidden');
            // 不清除currentResource，因为可能需要在后续步骤使用
        }
        
        // 自定义名称输入框显示/隐藏逻辑
        scrapeSourceRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (customNameContainer) {
                    if (this.value === 'custom-name') {
                        customNameContainer.classList.remove('hidden');
                        if (customMovieNameInput) customMovieNameInput.focus();
                    } else {
                        customNameContainer.classList.add('hidden');
                    }
                }
            });
        });
        
        // 关闭按钮事件
        if (closeModalBtn) closeModalBtn.addEventListener('click', closeModal);
        
        // 取消按钮事件
        if (cancelScrapeBtn) cancelScrapeBtn.addEventListener('click', closeModal);
        
        // 确认刮削按钮事件
        if (confirmScrapeBtn) {
            confirmScrapeBtn.addEventListener('click', function() {
                if (!currentResource) {
                    console.error('currentResource未设置，无法继续刮削');
                    window.showNotification('资源信息丢失，请重试', 'error');
                    return;
                }
                
                // 获取选择的刮削名称来源
                const selectedSource = document.querySelector('input[name="scrape-source"]:checked');
                if (!selectedSource) {
                    window.showNotification('请选择刮削名称来源', 'error');
                    return;
                }
                
                let movieName = '';
                
                // 根据选择的来源获取刮削名称
                if (selectedSource.value === 'folder-name') {
                    movieName = currentResource.name;
                } else if (selectedSource.value === 'file-name') {
                    movieName = currentResource.short_play_name;
                } else if (selectedSource.value === 'custom-name' && customMovieNameInput) {
                    movieName = customMovieNameInput.value.trim();
                    if (!movieName) {
                        window.showNotification('请输入自定义名称', 'error');
                        return;
                    }
                }
                
                // 保存电影名称
                currentScrapeMovieName = movieName;
                console.log('已设置刮削名称:', currentScrapeMovieName);
                
                // 关闭模态框
                closeModal();
                
                // 显示刮削方式选择模态框
                const methodModal = document.getElementById('scrape-method-modal');
                if (methodModal) {
                    methodModal.classList.remove('hidden');
                } else {
                    console.error('刮削方式模态框不存在');
                }
            });
        }
    }
    
    // 初始化刮削方式选择模态框
    function initScrapeMethodModal() {
        const methodModal = document.getElementById('scrape-method-modal');
        if (!methodModal) return; // 模态框不存在则不初始化
        
        const closeModalBtn = document.getElementById('close-method-modal');
        const cancelBtn = document.getElementById('cancel-method');
        const confirmBtn = document.getElementById('confirm-method');
        const scrapeMethodRadios = document.querySelectorAll('input[name="scrape-method"]');
        const tmdbMediaTypeContainer = document.getElementById('tmdb-media-type-container');
        
        // 监听刮削方式选择变化
        scrapeMethodRadios.forEach(radio => {
            radio.addEventListener('change', function() {
                if (this.value === 'tmdb') {
                    tmdbMediaTypeContainer.classList.remove('hidden');
                } else {
                    tmdbMediaTypeContainer.classList.add('hidden');
                }
            });
        });
        
        // 关闭模态框
        function closeModal() {
            methodModal.classList.add('hidden');
        }
        
        // 关闭按钮事件
        if (closeModalBtn) closeModalBtn.addEventListener('click', closeModal);
        
        // 取消按钮事件
        if (cancelBtn) cancelBtn.addEventListener('click', closeModal);
        
        // 确认按钮事件
        if (confirmBtn) {
            confirmBtn.addEventListener('click', function() {
                // 获取选择的刮削方式
                const selectedMethod = document.querySelector('input[name="scrape-method"]:checked');
                if (!selectedMethod) {
                    window.showNotification('请选择刮削方式', 'error');
                    return;
                }
                
                currentScrapeMethod = selectedMethod.value;
                console.log('已选择刮削方式:', currentScrapeMethod);
                
                // 如果是TMDB，获取媒体类型
                let tmdbMediaType = 'movie'; // 默认值
                if (currentScrapeMethod === 'tmdb') {
                    const selectedMediaType = document.querySelector('input[name="tmdb-media-type"]:checked');
                    if (selectedMediaType) {
                        tmdbMediaType = selectedMediaType.value;
                        console.log('已选择媒体类型:', tmdbMediaType);
                    }
                }
                
                // 关闭模态框
                closeModal();
                
                // 显示加载通知
                let notificationText = '';
                if (currentScrapeMethod === 'douban') {
                    notificationText = `正在使用豆瓣搜索: ${currentScrapeMovieName}`;
                } else if (currentScrapeMethod === 'tmdb') {
                    notificationText = `正在使用TMDB搜索${tmdbMediaType === 'movie' ? '电影' : '电视节目'}: ${currentScrapeMovieName}`;
                } else if (currentScrapeMethod === 'madouqu') {
                    notificationText = `正在使用国产刮削搜索: ${currentScrapeMovieName}`;
                } else if (currentScrapeMethod === 'javdb') {
                    notificationText = `正在使用其他刮削搜索: ${currentScrapeMovieName}`;
                } else {
                    notificationText = `正在搜索: ${currentScrapeMovieName}`;
                }
                window.showNotification(notificationText, 'info');
                
                // 执行搜索，传递媒体类型
                performSearch(currentScrapeMethod, currentScrapeMovieName, tmdbMediaType);
            });
        }
    }
    
    // 执行搜索
    function performSearch(method, query, tmdbMediaType = 'movie') {
        let apiUrl = '';
        
        if (method === 'douban') {
            apiUrl = `/api/douban/search?q=${encodeURIComponent(query)}`;
        } else if (method === 'tmdb') {
            apiUrl = `/api/tmdb/search?q=${encodeURIComponent(query)}&type=${tmdbMediaType}`;
        } else if (method === 'madouqu') {
            apiUrl = `/api/madouqu/search?q=${encodeURIComponent(query)}`;
        } else if (method === 'javdb') {
            apiUrl = `/api/javdb/search?q=${encodeURIComponent(query)}`;
        } else {
            window.showNotification('未知的刮削方式', 'error');
            return;
        }
        
        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.data && data.data.length > 0) {
                    // 显示搜索结果
                    displaySearchResults(data.data, method);
                } else {
                    window.showNotification('未找到相关电影信息', 'error');
                }
            })
            .catch(error => {
                console.error('搜索失败:', error);
                window.showNotification('搜索失败: ' + error.message, 'error');
            });
    }
    
    // 显示搜索结果
    function displaySearchResults(results, method) {
        const resultsContainer = document.getElementById('search-results-container');
        if (!resultsContainer) {
            console.error('搜索结果容器不存在');
            return;
        }
        
        resultsContainer.innerHTML = '';
        
        if (!results || results.length === 0) {
            resultsContainer.innerHTML = '<div class="text-center p-4 text-gray-500">未找到相关结果</div>';
            return;
        }
        
        results.forEach(result => {
            const resultItem = document.createElement('div');
            resultItem.className = 'p-4 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors';
            
            // 处理不同数据源的结果格式
            let title, year, imageUrl;
            if (method === 'douban') {
                title = result.title || result.subject_title;
                year = result.year || '';
                imageUrl = result.pic || result.img || '/static/images/placeholder.png';
            } else if (method === 'tmdb') {
                title = result.title || result.name;
                year = result.release_date ? new Date(result.release_date).getFullYear() : '';
                imageUrl = result.poster_url || '/static/images/placeholder.png';
            } else if (method === 'madouqu') {
                title = result.title || result.name;
                year = result.year || '';
                imageUrl = result.poster || result.image || '/static/images/placeholder.png';
            } else if (method === 'javdb') {
                title = result.title || result.name || result['标题'];
                year = result.year || '';
                imageUrl = result.poster || result.cover || result['封面图片链接'] || '/static/images/placeholder.png';
            }
            
            resultItem.innerHTML = `
                <div class="flex items-center p-2">
                    <div class="flex-grow">
                        <h4 class="font-medium text-lg">${title} ${year ? `(${year})` : ''}</h4>
                    </div>
                </div>
            `;
            
            // 添加点击事件
            resultItem.addEventListener('click', function() {
                // 保存当前媒体信息
                currentMediaInfo = {
                    method: method,
                    data: result,
                    details: null  // 初始化details为null，后续会填充
                };
                console.log('已选择搜索结果，当前媒体信息:', currentMediaInfo);
                
                // 关闭搜索结果模态框
                const resultsModal = document.getElementById('search-results-modal');
                if (resultsModal) resultsModal.classList.add('hidden');
                
                // 显示资源详情
                fetchResourceDetails(method, result);
            });
            
            resultsContainer.appendChild(resultItem);
        });
        
        // 显示搜索结果模态框
        const resultsModal = document.getElementById('search-results-modal');
        if (resultsModal) resultsModal.classList.remove('hidden');
    }
    
    // 初始化搜索结果模态框
    function initSearchResultsModal() {
        const resultsModal = document.getElementById('search-results-modal');
        if (!resultsModal) return; // 模态框不存在则不初始化
        
        const closeModalBtn = document.getElementById('close-results-modal');
        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', function() {
                resultsModal.classList.add('hidden');
            });
        }
    }
    
    // 删除临时海报文件
    function deleteTempPoster() {
        if (currentPosterFilename && !nfoGenerated) {
            fetch('/api/douban/delete-poster', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ filename: currentPosterFilename })
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .catch(error => {
                console.error('删除临时海报失败:', error);
            })
            .finally(() => {
                // 无论删除成功与否，都重置文件名
                currentPosterFilename = null;
            });
        }
    }
    
    // 获取资源详情
    function fetchResourceDetails(method, result) {
        let apiUrl = '';
        
        if (method === 'douban') {
            const movieUrl = result.url || result.target_url;
            if (!movieUrl) {
                window.showNotification('获取电影URL失败', 'error');
                return;
            }
            apiUrl = `/api/douban/detail?url=${encodeURIComponent(movieUrl)}`;
        } else if (method === 'tmdb') {
            const movieId = result.id;
            if (!movieId) {
                window.showNotification('获取电影ID失败', 'error');
                return;
            }
            const mediaType = result.type || 'movie';
            apiUrl = `/api/tmdb/detail?id=${movieId}&type=${mediaType}`;
        } else if (method === 'madouqu') {
            const movieUrl = result.url;
            if (!movieUrl) {
                window.showNotification('获取电影URL失败', 'error');
                return;
            }
            apiUrl = `/api/madouqu/detail?url=${encodeURIComponent(movieUrl)}`;
        } else if (method === 'javdb') {
            const code = result.code || result['番号'] || result.id;
            if (!code) {
                window.showNotification('获取电影番号失败', 'error');
                return;
            }
            // 构造符合API要求的URL格式，包含q查询参数
            const searchUrl = 'https://javdb.com/search?q=' + code;
            apiUrl = `/api/javdb/detail?url=${encodeURIComponent(searchUrl)}`;
        }
        
        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误，状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.data) {
                    // 保存详情到currentMediaInfo（关键：确保details被正确设置）
                    currentMediaInfo.details = data.data;
                    console.log('已获取资源详情，currentMediaInfo:', currentMediaInfo);
                    // 显示资源详情
                    displayResourceDetails(data.data, method);
                } else {
                    window.showNotification('获取资源详情失败', 'error');
                }
            })
            .catch(error => {
                console.error('获取资源详情失败:', error);
                window.showNotification('获取资源详情失败: ' + error.message, 'error');
            });
    }
    
    // 显示资源详情
    function displayResourceDetails(details, method) {
        const titleElement = document.getElementById('detail-title');
        const infoElement = document.getElementById('detail-info');
        const overviewElement = document.getElementById('detail-overview');
        const posterContainer = document.getElementById('poster-container');
        
        // 检查必要元素是否存在
        if (!titleElement || !infoElement || !overviewElement || !posterContainer) {
            console.error('资源详情模态框元素不完整');
            return;
        }
        
        // 处理不同数据源的详情格式
        let title, originalTitle, directors, writers, actors, genres, countries, releaseDate, runtime, overview, posterUrl;
        
        if (method === 'douban') {
            title = details.title;
            originalTitle = details.originaltitle;
            directors = details.directors || [];
            writers = details.writers || [];
            actors = details.actors || [];
            genres = details.genres || [];
            countries = details.countries || [];
            releaseDate = details.release_date;
            runtime = details.runtime;
            overview = details.introduction;
            posterUrl = details.poster_url;
        } else if (method === 'tmdb') {
            title = details.title || details.name;
            originalTitle = details.original_title || details.original_name;
            directors = details.directors || details.creators || [];
            writers = details.writers || [];
            actors = details.actors ? details.actors.map(a => a.name) : [];
            genres = details.genres || [];
            countries = details.countries || [];
            releaseDate = details.release_date || details.first_air_date;
            runtime = details.runtime;
            overview = details.overview;
            posterUrl = details.poster_url;
        } else if (method === 'madouqu') {
            title = details.title || '未知标题';
            originalTitle = '';
            directors = details.directors || [];
            writers = [];
            actors = details.actors ? [details.actors] : [];
            genres = details.genres || [];
            countries = ['中国'];
            releaseDate = '';
            runtime = '';
            // 不显示简介
            overview = '';
            posterUrl = details.poster_url || details.cover || '/static/images/placeholder.png';
            // 保存番号信息 - 从搜索关键词或其他地方获取
            if (details.code) {
                currentMediaInfo.details.code = details.code;
            } else if (details.id) {
                currentMediaInfo.details.code = details.id;
            } else if (currentScrapeMovieName) {
                // 使用搜索关键词作为备用番号
                currentMediaInfo.details.code = currentScrapeMovieName;
            }
        } else if (method === 'javdb') {
            title = details.title || details['标题'] || '未知标题';
            originalTitle = '';
            directors = details.directors ? details.directors : [details['导演'] || ''];
            writers = [];
            actors = details.actors ? details.actors : [details['演员'] || ''];
            genres = details.genres || details.category || (details['类别'] ? [details['类别']] : []);
            countries = ['日本'];
            releaseDate = details.release_date || details['日期'] || '';
            runtime = details.runtime || details.duration || details['时长'] || '';
            overview = '';
            posterUrl = details.poster_url || details['封面图片链接'] || details.poster || details.cover || '/static/images/placeholder.png';
            // 保存番号信息
            currentMediaInfo.details.code = details.code || details['番号'] || details.id;
            // 保存片商和发行商信息
            currentMediaInfo.details.studio = details.studio || details['片商'] || '';
            currentMediaInfo.details.publisher = details.publisher || details['发行商'] || '';
        }
        
        // 更新标题
        titleElement.textContent = title || '未知标题';
        
        // 更新信息
        let infoHtml = '';
        if (originalTitle && originalTitle !== title) {
            infoHtml += `<div><strong>原名:</strong> ${originalTitle}</div>`;
        }
        // 显示番号信息（针对国产刮削和其他刮削）
        if ((method === 'madouqu' || method === 'javdb') && currentMediaInfo.details.code) {
            infoHtml += `<div><strong>番号:</strong> ${currentMediaInfo.details.code}</div>`;
        }
        if (releaseDate) {
            infoHtml += `<div><strong>日期:</strong> ${releaseDate}</div>`;
            const year = new Date(releaseDate).getFullYear();
            infoHtml += `<div><strong>年份:</strong> ${year}</div>`;
        }
        if (runtime) {
            infoHtml += `<div><strong>时长:</strong> ${runtime} 分钟</div>`;
        }
        if (genres && genres.length > 0) {
            infoHtml += `<div><strong>类别:</strong> ${genres.join(', ')}</div>`;
        }
        if (directors && directors.length > 0) {
            infoHtml += `<div><strong>导演:</strong> ${directors.join(', ')}</div>`;
        }
        if (writers && writers.length > 0) {
            infoHtml += `<div><strong>编剧:</strong> ${writers.join(', ')}</div>`;
        }
        if (actors && actors.length > 0) {
            // 对于国产刮削和其他刮削，确保演员信息正确显示
            if ((method === 'madouqu' || method === 'javdb') && actors[0] === '') {
                infoHtml += `<div><strong>演员:</strong> </div>`;
            } else {
                infoHtml += `<div><strong>演员:</strong> ${actors.slice(0, 5).join(', ')}${actors.length > 5 ? '...' : ''}</div>`;
            }
        }
        // 显示片商和发行商信息（JavDB专属）
        if (method === 'javdb') {
            if (currentMediaInfo.details.studio) {
                infoHtml += `<div><strong>片商:</strong> ${currentMediaInfo.details.studio}</div>`;
            }
            if (currentMediaInfo.details.publisher) {
                infoHtml += `<div><strong>发行:</strong> ${currentMediaInfo.details.publisher}</div>`;
            }
        }
        if (countries && countries.length > 0) {
            infoHtml += `<div><strong>国家/地区:</strong> ${countries.join(', ')}</div>`;
        }
        
        infoElement.innerHTML = infoHtml;
        
        // 不显示简介
        overviewElement.textContent = '';
        
        // 更新海报
        if (method === 'douban') {
            // 豆瓣数据源使用临时海报文件管理机制
            if (posterUrl) {
                // 删除之前的临时海报文件（如果存在）
                deleteTempPoster();
                
                // 尝试通过后端API下载海报
                const movieId = details.douban_id || details.url.split('/').filter(Boolean).pop();
                const title = details.title || '电影';
                
                if (!movieId) {
                    console.error('无法获取电影ID');
                    posterContainer.innerHTML = `<img src="/static/images/placeholder.png" alt="${title}" class="w-full h-full object-cover">`;
                    return;
                }
                
                // 构建后端下载海报的API URL
                const safeMovieId = movieId.replace(/[\/:*?"<>|]/g, '');
                const downloadUrl = '/api/douban/download-poster?url=' + encodeURIComponent(posterUrl) + '&id=' + encodeURIComponent(safeMovieId) + '&title=' + encodeURIComponent(title);
                
                // 发送请求到后端下载海报
                fetch(downloadUrl)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.local_path && data.filename) {
                            // 保存文件名用于后续删除
                            currentPosterFilename = data.filename;
                            // 重置NFO生成标记
                            nfoGenerated = false;
                            
                            // 构建本地访问路径
                            const filename = data.local_path.split('/').pop();
                            const localImageUrl = '/data/images/' + encodeURIComponent(filename);
                            posterContainer.innerHTML = `
                                <img src="${localImageUrl}" alt="${title}" class="w-full h-full object-cover">
                            `;
                        } else {
                            // 失败时使用占位图
                            posterContainer.innerHTML = `
                                <img src="/static/images/placeholder.png" alt="${title}" class="w-full h-full object-cover">
                            `;
                            // 重置海报文件信息
                            currentPosterFilename = null;
                        }
                    })
                    .catch(error => {
                        console.error('下载海报失败:', error);
                        // 出错时使用占位图
                        posterContainer.innerHTML = `
                            <img src="/static/images/placeholder.png" alt="${title}" class="w-full h-full object-cover">
                        `;
                    });
            } else {
                posterContainer.innerHTML = `
                    <img src="/static/images/placeholder.png" alt="${title || '未知电影'}" class="w-full h-full object-cover">
                `;
            }
        } else {
            // 其他数据源（如TMDB）保持原有逻辑
            posterContainer.innerHTML = `
                <img src="${posterUrl || '/static/images/placeholder.png'}" alt="${title || '未知电影'}" class="w-full h-full object-cover">
            `;
        }
        
        // 保存详情信息
        currentMediaInfo.details = details;
        
        // 显示详情模态框
        const detailModal = document.getElementById('resource-detail-modal');
        if (detailModal) {
            detailModal.classList.remove('hidden');
            console.log('资源详情模态框已显示，生成NFO按钮应可点击');
        } else {
            console.error('资源详情模态框不存在');
        }
    }
    
    // 初始化资源详情模态框（关键修复：确保按钮事件正确绑定）
    function initResourceDetailModal() {
        const detailModal = document.getElementById('resource-detail-modal');
        if (!detailModal) {
            console.error('资源详情模态框不存在，无法初始化');
            return;
        }
        
        const closeModalBtn = document.getElementById('close-detail-modal');
        const generateNfoBtn = document.getElementById('generate-nfo-btn');
        
        // 检查生成NFO按钮是否存在
        if (!generateNfoBtn) {
            console.error('生成NFO按钮元素不存在，请检查HTML');
            return;
        }
        
        // 关闭模态框
        if (closeModalBtn) {
            closeModalBtn.addEventListener('click', function() {
                detailModal.classList.add('hidden');
                // 删除临时海报文件（如果未生成NFO）
                deleteTempPoster();
            });
        }
        
        // 生成NFO按钮事件（关键：确保事件正确绑定并添加调试日志）
        generateNfoBtn.addEventListener('click', function() {
            console.log('生成NFO按钮被点击，检查状态:', {
                currentResource: !!currentResource,
                currentMediaInfo: !!currentMediaInfo,
                hasDetails: currentMediaInfo ? !!currentMediaInfo.details : false
            });
            
            // 检查必要条件
            if (!currentResource) {
                window.showNotification('未找到资源信息', 'error');
                return;
            }
            if (!currentMediaInfo || !currentMediaInfo.details) {
                window.showNotification('未找到媒体详情', 'error');
                return;
            }
            
            // 如果是豆瓣数据源，标记NFO已生成，保留海报文件
            if (currentMediaInfo.method === 'douban') {
                nfoGenerated = true;
            }
            
            // 关闭详情模态框
            detailModal.classList.add('hidden');
            
            // 显示刮削进度模态框
            const progressModal = document.getElementById('scrape-progress-modal');
            if (progressModal) {
                progressModal.classList.remove('hidden');
            } else {
                console.error('刮削进度模态框不存在');
            }
            
            // 重置进度状态
            resetProgressStatus();
            
            // 执行刮削和保存
            performScrapeAndSave();
        });
        
        console.log('生成NFO按钮事件已绑定');
    }
    
    // 重置进度状态
    function resetProgressStatus() {
        const nfoStatus = document.getElementById('nfo-status');
        const posterStatus = document.getElementById('poster-status');
        const folderStatus = document.getElementById('folder-status');
        const organizeStatus = document.getElementById('organize-status');
        const overallStatus = document.getElementById('overall-status');
        
        if (nfoStatus) nfoStatus.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 进行中';
        if (posterStatus) posterStatus.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 进行中';
        if (folderStatus) folderStatus.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 进行中';
        if (organizeStatus) organizeStatus.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 进行中';
        if (overallStatus) overallStatus.innerHTML = '<p>刮削进行中，请稍候...</p>';
    }
    
    // 更新进度状态
    function updateProgressStatus(step, success) {
        const statusId = `${step}-status`;
        const statusElement = document.getElementById(statusId);
        
        if (statusElement) {
            if (success) {
                statusElement.innerHTML = '<i class="fa fa-check text-green-500"></i> 完成';
            } else {
                statusElement.innerHTML = '<i class="fa fa-times text-red-500"></i> 失败';
                const overallStatus = document.getElementById('overall-status');
                if (overallStatus) {
                    overallStatus.innerHTML = '<p class="text-red-500">刮削失败，请重试</p>';
                }
            }
        }
    }
    
    // 执行刮削和保存
    function performScrapeAndSave() {
        console.log('开始执行刮削和保存操作');
        const method = currentMediaInfo.method;
        const details = currentMediaInfo.details;
        
        if (!method || !details) {
            window.showNotification('缺少媒体信息', 'error');
            return;
        }
        
        let nfoPromise;
        
        // 根据不同的数据源生成NFO
        if (method === 'douban') {
            // 豆瓣数据源
            nfoPromise = fetch('/api/douban/generate-nfo', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ url: details.url })
            });
        } else if (method === 'tmdb') {
            // TMDB数据源
            nfoPromise = fetch('/api/tmdb/generate-nfo', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: details.id, media_type: details.type || 'movie' })
            });
        } else if (method === 'madouqu') {
            // 国产刮削数据源 - 修复生成NFO的400错误，使用正确的API路径和参数
            const code = details.code || currentScrapeMovieName || 'unknown';
            nfoPromise = fetch(`/api/madouqu/generate_nfo?code=${encodeURIComponent(code)}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
        } else if (method === 'javdb') {
            // 其他刮削数据源 - 修复生成NFO的400错误
            nfoPromise = fetch('/api/javdb/generate-nfo', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ code: details.code || details['番号'] || details.id })
            });
        } else {
            window.showNotification('未知的刮削方式', 'error');
            return;
        }
        
        nfoPromise
            .then(response => {
                // 记录响应状态
                console.log('NFO生成API响应状态:', response.status);
                if (!response.ok) {
                    throw new Error(`生成NFO失败，状态码: ${response.status}`);
                }
                return response.json().catch(error => {
                    // 处理JSON解析错误
                    console.error('NFO响应JSON解析错误:', error);
                    // 尝试获取响应文本
                    return response.text().then(text => {
                        console.log('NFO响应原始文本:', text);
                        throw new Error(`NFO响应格式错误: ${text.substring(0, 100)}`);
                    });
                });
            })
            .then(data => {
                console.log('NFO生成响应数据:', data);
                if (data && (data.success || data.data)) {
                    // 更新NFO状态
                    updateProgressStatus('nfo', true);
                    
                    // 获取生成的电影信息、海报路径和NFO路径
                    // 确保movieInfo包含完整的电影详情信息
                    const movieInfo = {
                        ...(data.data?.movie_info || {}),  // 安全获取movie_info
                        nfo_path: data.data?.nfo_path || data.nfo_path,
                        // 直接使用currentMediaInfo中的details作为备用，确保有完整的电影信息
                        ...currentMediaInfo.details,
                        // 添加一个标记，表明这是来自哪个数据源的信息
                        source: method
                    };
                    console.log('构建的movieInfo对象:', movieInfo);
                    // 安全获取poster_path，避免undefined访问错误
                    let posterPath = data.data?.poster_path || '';
                    
                    // 对于国产刮削数据源，我们需要特殊处理海报
                    if ((method === 'madouqu' || method === 'javdb') && currentMediaInfo.details && currentMediaInfo.details.poster_url) {
                        console.log('国产刮削数据源，尝试通过专用API下载海报');
                        
                        // 构建海报下载API的URL
                        const apiPath = method === 'madouqu' ? '/api/madouqu/download-poster' : '/api/javdb/download-poster';
                        const movieId = currentMediaInfo.details.code || currentMediaInfo.details.id || 'unknown';
                        const title = currentMediaInfo.details.title || '未知电影';
                        
                        // 调用专用API下载海报
                        return fetch(`${apiPath}?url=${encodeURIComponent(currentMediaInfo.details.poster_url)}&id=${encodeURIComponent(movieId)}&title=${encodeURIComponent(title)}`)
                            .then(response => response.json())
                            .then(posterData => {
                                if (posterData.success && posterData.local_path) {
                                    console.log('海报下载成功，本地路径:', posterData.local_path);
                                    // 使用绝对路径格式，确保后端能正确找到文件
                                    posterPath = posterData.local_path;
                                } else {
                                    console.error('海报下载失败:', posterData.message || '未知错误');
                                }
                                
                                // 无论海报是否下载成功，都继续保存刮削数据
                                return saveScrapedDataToResource(currentResource, movieInfo, posterPath);
                            })
                            .catch(error => {
                                console.error('下载海报时发生错误:', error);
                                // 即使海报下载失败，也继续保存刮削数据
                                return saveScrapedDataToResource(currentResource, movieInfo, posterPath);
                            });
                    } else {
                        // 其他数据源正常处理
                        return saveScrapedDataToResource(currentResource, movieInfo, posterPath);
                    }
                } else {
                    updateProgressStatus('nfo', false);
                    throw new Error(data.message || '生成NFO失败');
                }
            })
            .then(result => {
                // 确保结果是成功的
                if (result && result.success === true) {
                    console.log('刮削数据保存成功结果:', result);
                    
                    // 更新所有进度状态
                    updateProgressStatus('poster', true);
                    updateProgressStatus('folder', true);
                    updateProgressStatus('organize', true);
                    
                    // 更新总体状态
                    const overallStatus = document.getElementById('overall-status');
                    if (overallStatus) {
                        overallStatus.innerHTML = '<p class="text-green-500">刮削成功！</p>';
                    }
                    
                    // 显示成功通知
                    window.showNotification('刮削成功', 'success');
                    
                    // 刷新资源列表
                    setTimeout(() => {
                        // 关闭进度模态框
                        const progressModal = document.getElementById('scrape-progress-modal');
                        if (progressModal) progressModal.classList.add('hidden');
                        // 刷新资源列表
                        loadLocalResources(true);
                    }, 1500);
                } else {
                    // 即使返回了结果，但success不是true，也视为失败
                    console.error('刮削数据保存失败，结果:', result);
                    updateProgressStatus('poster', false);
                    updateProgressStatus('folder', false);
                    updateProgressStatus('organize', false);
                    
                    // 更新总体状态
                    const overallStatus = document.getElementById('overall-status');
                    if (overallStatus) {
                        overallStatus.innerHTML = '<p class="text-red-500">刮削失败！</p>';
                    }
                    
                    window.showNotification('保存刮削数据失败', 'error');
                    
                    // 5秒后自动关闭进度模态框
                    setTimeout(() => {
                        const progressModal = document.getElementById('scrape-progress-modal');
                        if (progressModal) progressModal.classList.add('hidden');
                    }, 5000);
                }
            })
            .catch(error => {
                console.error('刮削失败:', error);
                window.showNotification('刮削失败: ' + error.message, 'error');
                updateProgressStatus('nfo', false);
                
                // 5秒后自动关闭进度模态框
                setTimeout(() => {
                    const progressModal = document.getElementById('scrape-progress-modal');
                    if (progressModal) progressModal.classList.add('hidden');
                }, 5000);
            });
    }
    
    // 保存刮削数据到资源目录
    function saveScrapedDataToResource(resource, movieInfo, posterPath) {
        console.log('准备保存刮削数据:', {
            resource_path: resource.path,
            has_movie_info: !!movieInfo,
            has_poster_path: !!posterPath,
            source: movieInfo?.source || currentMediaInfo.method
        });
        
        // 调用API端点来保存刮削数据
        return fetch('/api/local-resources/save-scraped-data', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                resource_path: resource.path,
                movie_info: movieInfo,
                poster_path: posterPath,
                // 确保传递source字段给后端
                source: movieInfo?.source || currentMediaInfo.method
            })
        })
        .then(response => {
            console.log('保存刮削数据API响应状态:', response.status);
            if (!response.ok) {
                // 尝试获取更多错误详情
                return response.text().then(text => {
                    throw new Error(`保存刮削数据失败，状态码: ${response.status}, 详情: ${text.substring(0, 200)}`);
                });
            }
            return response.text().then(text => {
                console.log('保存数据响应原始文本:', text);
                try {
                    // 尝试解析JSON
                    return JSON.parse(text);
                } catch (error) {
                    console.error('保存数据响应JSON解析错误:', error);
                    // 尝试从纯文本响应中提取成功信息
                    if (text.includes('成功') || text.includes('已保存')) {
                        console.log('响应文本包含成功信息，视为保存成功');
                        return { success: true, message: '刮削数据保存成功' };
                    }
                    throw new Error(`保存数据响应格式错误: ${text.substring(0, 100)}`);
                }
            });
        })
        .then(data => {
            console.log('保存刮削数据响应:', data);
            // 增强的成功判断逻辑，适用于不同数据源的响应格式
            const isSuccess = data && (
                data.success === true || 
                data.result === 'success' || 
                (data.data && data.data.progress && !data.data.progress.error) ||
                (typeof data === 'object' && !data.error)
            );
            
            if (isSuccess) {
                console.log('刮削数据保存成功，文件夹创建和文件移动操作已完成');
                // 清除相关缓存，确保刷新页面后能看到最新数据
                clearRelatedCache(resource.path);
                return { success: true, data: data.data };
            } else {
                const errorMessage = data.message || data.error || '保存刮削数据失败';
                throw new Error(errorMessage);
            }
        })
        .catch(error => {
            console.error('保存刮削数据时发生错误:', error);
            throw error;
        });
    }
    
    // 渲染错误信息
    function renderErrorMessage(message) {
        if (!resourcesTableBody) return;
        
        resourcesTableBody.innerHTML = `
            <tr>
                <td colspan="8" class="text-center p-8 text-gray-500">
                    <i class="fa fa-exclamation-circle text-4xl mb-2 text-red-500"></i>
                    <p>${message}</p>
                    <p class="text-sm mt-2">请检查目录配置或网络连接</p>
                </td>
            </tr>
        `;
    }
    
    // 显示/隐藏加载状态
    function showLoading(show) {
        if (!resourcesTableBody) return;
        
        if (show) {
            // 如果是首次加载，显示加载动画
            if (resourcesTableBody.querySelector('td[colspan="8"]')) {
                resourcesTableBody.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center p-8 text-gray-500">
                            <i class="fa fa-circle-o-notch fa-spin text-4xl mb-2"></i>
                            <p>加载中...</p>
                        </td>
                    </tr>
                `;
            }
        }
    }
    
    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
});